package inits

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"im/appconfig"
	"im/global"
	"im/model"
	"log"
	"sync"
)

var (
	err  error
	once sync.Once
)

func InitMysql() {
	once.Do(func() {
		data := appconfig.ConfigData.Mysql
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
			data.User, data.Pass, data.Host, data.Port, data.Database)
		global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
		global.DB.SetMaxIdleConns(10)
		global.DB.SetMaxOpenConns(100)
		if err != nil {
			panic("数据库连接失败")
		} else {
			log.Println("数据库连接成功")
		}
		err = global.DB.AutoMigrate(&model.User{}, &model.Friend{}, &model.FriendAdd{})
		if err != nil {
			panic("数据库迁移失败")
		} else {
			log.Println("数据库迁移成功")
		}
	})
}
